<template>
  <div class="right-content">
    <Spin :spinning="spinning">
      <div style="display: flex; justify-content: space-between; width: 100%">
        <slot></slot>
        <div class="detail-row row-r">
          <div v-for="(item, index) in details" :key="index" class="row-col">
            {{ item.title }}：<span style="color: #a3a3a3">{{ item.value || '-' }}</span>
          </div>
        </div>
      </div>
    </Spin>
    <!-- <Row class="border-com mt1" :gutter="[12, 12]"> -->
    <div class="border-com mt1" style="margin: 1em -6px 0">
      <Tabs v-model:active-key="activeKey" @change="changeTabs">
        <TabPane :tab="item.title" v-for="(item, index) in tabsList" :key="index">
          <TablesCom
            :columns="item.columns"
            :api="item.api"
            :params="item.params"
            :pagination="item.pagination"
            @success="item.success"
            :useSearchForm="true"
            :actionColumn="item.cz"
            :actionColumnWidth="item.actionColumnWidth"
            :rowSelection="item.rowSelection"
            :rowKey="item.rowKey"
            :loading="item.loading"
            :formConfig="item.formConfig"
            @selection-change="item.selectionChange"
          >
            <template #tableTitle v-if="activeKey === 3">
              <Button
                type="primary"
                @click="handleBatchOutTable"
                :disabled="!selectedWaterCodes.length"
                >批量退表</Button
              >
            </template>

            <!-- <template #headerCell="{ column }">
              <div v-if="searchProptypeArr.includes(column.dataIndex)">
                <SearchInput
                  :column="column"
                  @search="handleSearch"
                  @reset="handleReset"
                  v-model:value="searchObj"
                />
              </div>
            </template> -->
            <template #action="{ rowData }" v-if="item.cz">
              <TableAction :actions="item.actions(rowData)" />
            </template>
          </TablesCom>
        </TabPane>
        <template #rightExtra>
          <Space>
            <template v-if="activeKey === 1 && scan">
              <Button @click="qrBox">扫码编箱</Button>
              <!-- <Button @click="showConfirm">手动编箱</Button> -->
            </template>
            <Button @click="refreshData" :loading="refreshLoading">刷新</Button>
          </Space>
        </template>
      </Tabs>
    </div>
    <!-- </Row> -->
    <ModalDetails @register="registerModal" />
    <QrBoxPlait @register="registerQrBoxPlait" @success="qrSuccess" :record="record" />
    <ManualWork @register="registerManualWork" @success="mergeSuccess" />
    <RecheckDetails @register="registerRecheckModal" />
  </div>
</template>

<script setup lang="ts">
  import { ref, unref, toRefs, watch, onBeforeMount, createVNode, nextTick } from 'vue';
  import { Tabs, TabPane, Button, Space, Spin, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import TablesCom from './TablesCom.vue';
  import { TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import ModalDetails from './ModalDetails.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import SearchInput from './search.vue';

  import {
    // getTaskEncasement,
    getRecheckWaterMeterHandle,
    submitWaterReturnTable,
    submitTaskErroneous,
  } from '/@/api/jd/water-box';
  import QrBoxPlait from './QrBoxPlait.vue';
  import ManualWork from './ManualWork.vue';
  import RecheckDetails from './RecheckDetails.vue';
  import {
    CommonParam,
    // SearchParams
  } from '../types';
  // import { BasicColumn } from '/@/components/Table';
  import { DICT } from '/@/enums/dict';
  import { getDictTypeListApi } from '/@/api/admin/dict';
  import { cloneDeep } from 'lodash-es';

  import {
    getPackagedWaterList,
    getStandardList,
    getDisqualification,
    getPendingVerification,
    getRecheckList,
    getTaskApply,
    getRetreatWaterMeterList,
    submitRefreshData,
  } from '/@/api/jd/water-box';
  import {
    rightSchemsColumn1,
    rightSearchSchems1,
    rightSchemsColumn2,
    // rightSearchSchems2,
    rightSchemsColumn3,
    // rightSearchSchems3,
    rightSchemsColumn4,
    // rightSearchSchems4,
    rightSchemsColumn5,
    // rightSearchSchems5,
  } from '../index.data';

  const $props = defineProps({
    boxCode: {
      type: String,
      default: '',
    },
    record: {
      type: Object,
      default: () => {},
    },
    leftReload: {
      type: Function,
      default: () => {},
    },
    userName: {
      type: String,
      default: '',
    },
    scan: {
      type: Boolean,
      default: true,
    },
  });

  const { record } = toRefs($props);

  // const searchProptypeArr = ['waterMeterCode', 'operator', 'deviceNumber', 'boxCode']; //需要显示搜索框的表头

  const { createMessage } = useMessage();

  const activeKey = ref(0);

  const details = ref<CommonParam[]>([]);

  const restApi = {};

  const refreshLoading = ref(false);

  const spinning = ref<boolean>(false);

  const paramsObj = { taskId: unref(record)?.task_id };

  const waterMeterCodes = ref([]);

  let nowSelectRowKey: boolean | string = '';
  let selectAllData: any[] = [];

  const [registerModal, { openModal }] = useModal();

  const [registerQrBoxPlait, { openModal: openQrBoxPlait }] = useModal();

  const [registerManualWork, { openModal: openManualWork }] = useModal();

  const [registerRecheckModal, { openModal: openRecheckWork }] = useModal();

  const selectedWaterCodes = ref<string[]>([]);

  const searchObj = ref<any>({});

  const setTableLoading = (activekey: number, loading: boolean) => {
    tabsList.value[activekey]['loading'] = loading;
  };
  const tabsList = ref<any[]>([]);

  async function dict() {
    const ret = await getDictTypeListApi({ type: DICT.WATER_METER_STATUS });
    tabsList.value = [
      {
        id: 1,
        title: '已编箱水表',
        columns: rightSchemsColumn1,
        formConfig: {
          schemas: rightSearchSchems1,
        },
        api: getPackagedWaterList,
        params: paramsObj,
        pagination: true,
        success: (val) => {
          restApi[0] = val;
          val.searchForm({
            operator: $props.userName,
          });
        },
        actionColumnWidth: 60,
        cz: true,

        actions: (rowData) => [
          {
            label: '详情',
            onClick: handleDetails.bind(null, rowData),
          },
        ],
      },
      {
        id: 2,
        title: '合格未编箱',
        actionColumnWidth: 60,
        columns: rightSchemsColumn2,
        formConfig: {
          schemas: rightSearchSchems1,
        },
        api: getStandardList,
        params: paramsObj,
        success: (val) => {
          restApi[1] = val;
          val.searchForm({
            operator: $props.userName,
          });
        },
        rowSelection: {
          type: 'checkbox',
        },
        rowKey: 'waterMeterCode',
        selectionChange: ({ rows }) => {
          waterMeterCodes.value = rows.map((i) => i.waterMeterCode);
        },
        cz: true,
        actions: (rowData) => [
          {
            label: '详情',
            onClick: handleDetails.bind(null, rowData),
          },
        ],
      },
      {
        id: 3,
        title: '不合格',

        columns: rightSchemsColumn3,
        formConfig: {
          schemas: rightSearchSchems1,
        },
        api: getDisqualification,
        params: paramsObj,

        success: (val) => {
          restApi[2] = val;
          val.searchForm({
            operator: $props.userName,
          });
        },
        actionColumnWidth: 160,
        cz: true,
        actions: (rowData) => [
          {
            label: '详情',
            onClick: handleDetails.bind(null, rowData),
          },
          {
            label: '复检',
            ifShow: rowData.audit === '0',
            onClick: handleRecheck.bind(null, rowData),
          },
          {
            label: '误判',
            ifShow: rowData.audit === '0',
            onClick: handleMisjudge.bind(null, rowData),
          },
        ],
      },
      {
        id: 4,
        title: '待检定水表',
        columns: rightSchemsColumn4(ret),
        formConfig: {
          schemas: rightSearchSchems1,
        },
        actionColumnWidth: 60,
        api: getPendingVerification,
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys: selectedWaterCodes,
          onChange: (selectedRowKeys: string[]) => {
            console.log(selectedWaterCodes.value, selectedRowKeys, nowSelectRowKey);

            if (nowSelectRowKey === true) {
              // 全选
              const arr = cloneDeep(selectedWaterCodes.value);
              selectedRowKeys.forEach((i) => {
                if (!selectedWaterCodes.value.includes(i)) {
                  arr.push(i);
                }
              });
              nowSelectRowKey = '';
              selectedWaterCodes.value = arr;
              return;
            }

            if (nowSelectRowKey === false) {
              // 当前页全取消选择
              const arr: string[] = [];
              selectAllData.forEach((i) => {
                if (!selectedWaterCodes.value.includes(i)) {
                  arr.push(i);
                }
              });
              selectAllData = [];
              nowSelectRowKey = '';
              selectedWaterCodes.value = arr;
              return;
            }

            if (!selectedRowKeys.length && nowSelectRowKey) {
              // 单选
              selectedWaterCodes.value = selectedWaterCodes.value.filter(
                (i) => i != nowSelectRowKey,
              );
              nowSelectRowKey = '';
            } else {
              if (nowSelectRowKey) {
                if (!selectedWaterCodes.value.includes(nowSelectRowKey as string)) {
                  selectedWaterCodes.value.push(...selectedRowKeys);
                } else {
                  selectedWaterCodes.value = selectedWaterCodes.value.filter(
                    (i) => i != nowSelectRowKey,
                  );
                }
              }
            }
          },
          onSelect: (selectKey) => {
            nowSelectRowKey = selectKey.waterMeterId;
          },
          onSelectAll: (data, _, changeRows) => {
            nowSelectRowKey = data;
            selectAllData = changeRows.map((i) => i.waterMeterId);
          },
        },
        rowKey: 'waterMeterId',
        params: paramsObj,
        // pagination: true,
        success: (val) => {
          restApi[3] = val;
          val.searchForm({
            operator: $props.userName,
          });
        },
        actions: (rowData) => [
          // {
          //   label: '手动检定',
          //   // onClick: handleDetails.bind(null, rowData),
          // },
          {
            label: '退表',
            onClick: handleReturnTable.bind(null, rowData),
          },
        ],
        cz: true,
      },

      {
        id: 5,
        title: '复检水表',
        columns: rightSchemsColumn5,
        formConfig: {
          schemas: rightSearchSchems1,
        },
        api: getRecheckList,
        params: paramsObj,
        pagination: false,
        actionColumnWidth: 140,
        success: (val) => {
          restApi[4] = val;
          val.searchForm({
            operator: $props.userName,
          });
        },
        cz: true,
        actions: (rowData) => [
          {
            label: '详情',
            onClick: handleRecheckDetails.bind(null, rowData),
          },
          { label: '人工审核', onClick: handleManualWork.bind(null, rowData) },
        ],
      },
      {
        id: 6,
        title: '退表水表',
        columns: rightSchemsColumn4(ret),
        formConfig: {
          schemas: rightSearchSchems1,
        },
        api: getRetreatWaterMeterList,
        params: paramsObj,

        success: (val) => {
          restApi[5] = val;
          val.searchForm({
            operator: $props.userName,
          });
        },
        cz: false,
      },
    ];
  }

  watch(
    () => $props.boxCode,
    (v) => {
      if (v) {
        // handleSearch({
        //   column: {
        //     dataIndex: 'boxCode',
        //   },
        //   value: v,
        // });
        handleSearch({
          boxCode: v,
        });
      }
    },
  );
  const changeTabs = (val) => {
    activeKey.value = val;
    searchObj.value = {};
    // setTableLoading(val, true);
    nextTick(() => {
      restApi[val] && restApi[val].reload();
    });
  };

  // 获取委托单详情
  const getApplyDetails = async () => {
    spinning.value = true;
    const ret = await getTaskApply($props.record.task_id);
    if ($props.scan) {
      details.value = [
        { title: '申请单号', value: ret.apply.applyOddNumbers },
        { title: '出厂编号', value: ret.apply.factoryNumber },
        { title: '委托单号', value: ret.task.taskOddNumbers },
        { title: '委托类型', value: ret.task.checkType },
        { title: '委托类别', value: ret.task.taskType },
        { title: '收样人/经办人', value: ret.task.createBy },
        { title: '实验室收样人', value: ret.task.userId },
        { title: '装箱数量', value: ret.task.boxNumber },
      ];
    } else {
      details.value = [
        { title: '申请单号', value: ret.apply.applyOddNumbers },
        { title: '出厂编号', value: ret.apply.factoryNumber },
        { title: '委托单号', value: ret.task.taskOddNumbers },
        { title: '收样人/经办人', value: ret.task.createBy },
        { title: '实验室收样人', value: ret.task.userId },
        { title: '评测类型', value: ret.task.testType },
      ];
    }

    spinning.value = false;
  };

  // 手动同步第三方数据给后端
  const refreshData = async () => {
    try {
      refreshLoading.value = true;
      await submitRefreshData(paramsObj.taskId);
      createMessage.success('操作成功');
    } finally {
      refreshLoading.value = false;
    }
  };

  // tabs切换
  const toggleActiveKey = (key: number) => {
    activeKey.value = key;
  };
  // 详情
  const handleDetails = (val) => {
    openModal(true, val);
  };

  // 复检详情
  const handleRecheckDetails = (val) => {
    console.log(val);

    openRecheckWork(true, { ...val, task_id: unref(record)?.task_id });
  };

  // 手动编箱
  // const showConfirm = () => {
  //   if (!unref(waterMeterCodes).length) {
  //     createMessage.warn('请选中需要编箱的表码！');
  //     return;
  //   }
  //   Modal.confirm({
  //     title: '编箱',
  //     content: `是否将选中的${unref(waterMeterCodes).length}个水表进行编箱`,
  //     async onOk() {
  //       await getTaskEncasement({
  //         taskId: unref(record).task_id,
  //         waterMeterCodes: unref(waterMeterCodes),
  //       });
  //       createMessage.success('操作成功');
  //       restApi[1].reload();
  //       $props.leftReload();
  //       Modal.destroyAll();
  //     },
  //     cancelText: '取消',
  //     onCancel() {
  //       Modal.destroyAll();
  //     },
  //   });
  // };

  // 扫码编箱
  const qrBox = () => {
    openQrBoxPlait(true, {
      task_id: unref(record).task_id,
    });
  };

  // 复检
  const handleRecheck = async (row) => {
    await getRecheckWaterMeterHandle(row.waterMeterId);
    createMessage.success('操作成功');
    restApi[2].reload();
    $props.leftReload();
  };

  // 人工审核
  const handleManualWork = (row) => {
    openManualWork(true, row);
  };

  onBeforeMount(() => {
    getApplyDetails();
    dict();
  });

  // 数据合并成功
  const mergeSuccess = () => {
    restApi[4].reload();

    $props.leftReload();
  };

  // 扫码装箱成功
  const qrSuccess = () => {
    restApi[1].reload();
    $props.leftReload();
  };

  // 退表
  const handleReturnTable = (data) => {
    waterReturnTable([data.waterMeterId]);
  };

  // 批量退表
  const handleBatchOutTable = () => {
    waterReturnTable(selectedWaterCodes.value, 2);
  };

  // 退表接口调用
  const waterReturnTable = (data: string[], type = 1) => {
    Modal.confirm({
      content: type === 1 ? '确定退表吗？' : '确定将所选水表退表吗？',
      icon: createVNode(ExclamationCircleOutlined),
      async onOk() {
        await submitWaterReturnTable({
          waterCodesArray: data,
          taskId: unref(record)?.task_id,
        });
        restApi[3].reload();
        createMessage.success('操作成功');
      },

      onCancel() {
        Modal.destroyAll();
      },
    });
  };

  // 误判
  const handleMisjudge = (data) => {
    Modal.confirm({
      content: '确定将当前水表设置为误判吗？',
      icon: createVNode(ExclamationCircleOutlined),
      async onOk() {
        await submitTaskErroneous({
          waterMeterId: data.waterMeterId,
          taskId: unref(record)?.task_id,
        });
        restApi[2].reload();
        createMessage.success('操作成功');
      },

      onCancel() {
        Modal.destroyAll();
      },
    });
  };

  // 查询
  const handleSearch = (val: any) => {
    // searchObj.value[val.column.dataIndex as string] = val.value;
    // tabsList.value[activeKey.value].params = {
    //   ...tabsList.value[activeKey.value].params,
    //   ...searchObj.value,
    // };
    // tabsList.value[activeKey.value].params = {
    //   ...tabsList.value[activeKey.value].params,
    //   ...searchObj.value,
    // };
    // nextTick(() => {
    //   restApi[activeKey.value].reload();
    // });
    nextTick(() => {
      restApi[activeKey.value].searchForm(val);
    });
  };
  // 重置
  // const handleReset = (val: BasicColumn) => {
  //   tabsList.value[activeKey.value].loading = true;
  //   searchObj.value[val.dataIndex as string] = '';
  //   tabsList.value[activeKey.value].params = {
  //     ...tabsList.value[activeKey.value].params,
  //     ...searchObj.value,
  //   };

  //   nextTick(() => {
  //     restApi[activeKey.value].reload();
  //   });
  // };

  defineExpose({ toggleActiveKey, restApi, activeKey, setTableLoading });
</script>

<style lang="less" scoped>
  .right-content {
    width: 70%;
    height: 100%;
    padding: 12px;

    .border-com {
      border: 1px solid #f0f0f0;
      border-radius: 4px;
      padding: 0 20px;
      box-shadow: 0 2px 5px 2px rgba(0, 0, 0, 0.1);
    }

    .mt1 {
      margin-top: 1em;
    }

    :deep(.ant-tabs-nav) {
      margin-bottom: 0 !important;
    }

    .detail-row {
      border: 1px solid #f0f0f0;
      border-radius: 4px;
      // height: 108px;
      padding: 4px 12px;
      overflow-y: auto;
      box-shadow: 0 2px 5px 2px rgba(0, 0, 0, 0.1);
      display: flex;
      flex-wrap: wrap;
      margin-left: -6px;
      margin-right: -6px;
      width: 100%;

      .row-col {
        width: 25%;
        padding: 4px 0;
      }
    }
  }

  :deep(.ant-form) {
    margin-bottom: 0 !important;
  }

  :deep(.ant-table-wrapper) {
    padding-top: 0 !important;
  }
</style>
